<?php

/**
 * WeEngine Api System
 *
 * (c) We7Team 2019 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace W7\Sdk\VSCode\Providers;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;
use W7\Sdk\VSCode\Console\VSTipCommand;
use W7\Sdk\VSCode\Controller\Middleware\LaravelMiddleware;
use W7\Sdk\VSCode\Exceptions\VSCodeExceptionHandler;
use W7\Sdk\VSCode\Exceptions\VSCodeLowVersionExceptionHandler;

class VSCodeServiceProvider extends ServiceProvider {
	public function boot() {
		if ($this->app->runningInConsole()) {
			$configPath = __DIR__ . '/../config/w7-vscode.php';
			$this->publishes([$configPath => config_path('w7-vscode.php')], 'w7-vscode');
			$this->commands([
				VSTipCommand::class
			]);
		}

		if (config('w7-vscode.enable')) {
			$this->loadRoutesFrom(__DIR__ . '/../route.php');
			$config = $this->app->make('config');
			$config->set('filesystems.disks.vscode', config('w7-vscode.filesystem'));

			$viewPath = __DIR__.'/../resources/views';
			$this->loadViewsFrom($viewPath, 'w7-vscode');
		}
	}

	public function register() {
		$configPath = __DIR__ . '/../config/w7-vscode.php';
		$this->mergeConfigFrom($configPath, 'w7-vscode');
		$this->app->alias(LaravelMiddleware::class, 'w7.vscode');

		if (config('w7-vscode.enable')) {
			$this->registerExceptionHandler();
		}
	}

	protected function registerExceptionHandler() {
		$previousHandler = null;
		if ($this->app->bound(ExceptionHandler::class) === true) {
			$previousHandler = $this->app->make(ExceptionHandler::class);
		}

		if (method_exists($this->app, 'version')) {
			if (version_compare($this->app->version(), '7.0', '>=')) {
				$this->app->singleton(ExceptionHandler::class, function () use ($previousHandler) {
					return new VSCodeExceptionHandler($previousHandler);
				});
			} else {
				$this->app->singleton(ExceptionHandler::class, function () use ($previousHandler) {
					return new VSCodeLowVersionExceptionHandler($previousHandler);
				});
			}
		}
	}

	/**
	 * Get the active router.
	 *
	 * @return Router
	 */
	protected function getRouter() {
		return $this->app['router'];
	}
}
